
import router from '@/router/router'
import store from '@/store/store'
import Qs from 'qs'

let util = {}

// console.log(process.env)
// 读取系统环境变量
const ajaxUrl = process.env.API_HOST;


util.ajax = axios.create({
    baseURL: ajaxUrl,
    timeout: 30000,
    headers: {'token': ''},
    transformRequest: function(data) {
        if(data.toLocaleString() == '[object FormData]'||isJSON(data))
            return data;  
            //  console.log(Qs.stringify(data,{ allowDots: true ,encode: false})); 
          return Qs.stringify(data)
    }
});

function isJSON(str) {
    if (typeof str == 'string') {
        try {
            JSON.parse(str);
            return true;
        } catch(e) {
            console.log(e);
            return false;
        }
    }
    console.log('It is not a string!')    
}

// 添加请求拦截器
util.ajax.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    let token = store.getters.getToken
    if(token){
        config.headers.token = token
    } else if(location.pathname.startsWith('/personal')){
        // router.push({name: 'login'})
    }
    return config;
  }, error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

  
// 添加响应拦截器
util.ajax.interceptors.response.use(response => {
    // 对响应数据做点什么
    if(response.data.msg == null)
        response.data.msg = ""
    if(response.data.rescode == null) {s
        response.data.rescode = -1
        response.data.msg = "服务器异常，请稍后再试"
    }
    if(response.data.rescode === 102){
        store.dispatch('removeToken', 'token')
        router.push({
            name: 'login'
        })
    }
    return response;
  }, error => {
    // 对响应错误做点什么
    return Promise.reject(error);
  });


export default util;